package com.xj.openapi4j.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xj.dao.InventoryDao;
import com.xj.entity.InvUpdateInfo;
import com.xj.openapi4j.service.token.U8Token;
import com.xj.openapi4j.service.token.YsToken;
import com.xj.openapi4j.util.HttpUtil;
import com.xj.openapi4j.util.RequestTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PriceJustService {
    @Value("${u8AppKey}")
    String u8AppKey;

    @Value("${u8AppSecret}")
    String u8AppSecret;
	@Autowired
    YsToken ysToken;
    @Autowired
    RedisTemplate redisTemplate;
    @Value("${fromAccount}")
    String from_account;
    @Autowired
    U8Token u8Token;
    @Autowired
    InventoryDao inventoryDao;
    private SimpleDateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   // 价格模板ID
    private  final  static long   priceTemplateId= 2034740422541049953L;

    public  void  transIncrement() throws Exception{
        List<InvUpdateInfo> list= inventoryDao.getInvUpdateInfoByCategory("pricejust");
        Set<String> set=list.stream().map(obj->obj.getCinvcode()).collect(Collectors.toSet());
        for(String vouchercode:set){
            transPriceJust(vouchercode);
        }
        inventoryDao.deleteAllInBatch(list);
    }

    public   void  transPriceJust(String  vouchercode) throws  Exception {
        boolean isExist=checkYS(vouchercode);
         if(isExist){
             log.info("商品调价单{}已在YS系统中同步过,不能再次同步",vouchercode);
             return;
         }
        Map<String,Object> map=inventoryDao.getPriceJustMainInfoBycode(vouchercode);
         if(map.get("id")==null){
             return;
         }
        String id=map.get("id").toString();
        List<Map<String,Object>> list=inventoryDao.getPriceJustDetailInfoBymainid(id);
        JSONObject  u8jsonObject=new JSONObject(map);
        JSONArray  u8jsonArray=new JSONArray(list);
        String token = ysToken.getToken();
        String requestUrl = "https://c3.yonyoucloud.com/iuap-api-auth/yonbip/sd/pricing/adjustment/save?access_token=" + token;
        JSONObject jsonObject = new JSONObject();
        JSONObject data = new JSONObject();
        data.put("_status", "Insert");
        //价格模块code
        data.put("priceTemplateId_name", "商品");
        //销售组织
     //   data.put("creationOrgId", "2034994435493724219");
        data.put("creationOrgId_name","上海东方药品科技实业有限公司");
        //调价单编码
        data.put("code", vouchercode);
        data.put("name", vouchercode);
        data.put("description", u8jsonObject.getString("cmainmemo"));
        data.put("createTime",sd.format(u8jsonObject.getDate("drdate")));
        data.put("beginDate",sd.format(u8jsonObject.getDate("ddate")));
        data.put("endDate","9999-12-31 23:59:59");
        JSONArray adjustDetails = new JSONArray();
        for(int i=0;i<u8jsonArray.size();i++){
            JSONObject  u8detail=u8jsonArray.getJSONObject(i);
            JSONObject detail = new JSONObject();
            detail.put("_status", "Insert");
            detail.put("priceTypeId_name", "商品价格1");
            detail.put("priceTypeCode", "PRODUCT");
            //币种
            detail.put("priceUnit_name", "人民币");
            //价格
            detail.put("adjustGradients_price", u8detail.getBigDecimal("iuprice1"));
            //计价单位
             detail.put("amountUnit_name",u8detail.getString("unitname") );
            //商品编码
             detail.put("dimension!productId_name", u8detail.getString("cinvcode"));
            detail.put("beginDate",u8detail.getDate("dstartdate")==null?null:sd.format(u8detail.getDate("dstartdate")));
            detail.put("endDate",u8detail.getDate("denddate")==null?null:sd.format(u8detail.getDate("denddate")));
            adjustDetails.add(detail);
        }
        data.put("adjustDetails",adjustDetails);
       jsonObject.put("data",data);
        String str= HttpUtil.post(requestUrl,jsonObject.toJSONString());
        log.info("trans prie just={}",str);
        JSONObject result=JSONObject.parseObject(str);
        JSONObject resultdata=result.getJSONObject("data");
        if(resultdata!=null && resultdata.getIntValue("sucessCount")>0){
            JSONArray infos=resultdata.getJSONArray("infos");
            for(int i=0;i<infos.size();i++){
                JSONObject info=infos.getJSONObject(i);
                long  voucherid=info.getLongValue("id");
                //审核调价单
                auditVouch(voucherid);
            }
        }
    }

    //审核调价单
    public  void  auditVouch  (long  id) throws Exception{
        String token = ysToken.getToken();
      String  url="https://c3.yonyoucloud.com/iuap-api-auth/yonbip/sd/pricing/adjustment/batchaudit?access_token="+token;
      JSONArray data=new JSONArray();
        JSONObject jsonObject=new JSONObject();
      jsonObject.put("id",id);
       data.add(jsonObject);
       JSONObject body=new JSONObject();
       body.put("data",data);
        String str= HttpUtil.post(url,body.toJSONString());
        log.info("audit respone={}",str);
    }

    private  boolean checkYS(String vouchercode) throws Exception{
        String token = ysToken.getToken();
        String  url="https://c3.yonyoucloud.com/iuap-api-auth/yonbip/sd/pricing/adjustment?access_token="+token;
        JSONObject param=new JSONObject();
        param.put("pageIndex",1);
        param.put("pageSize",10);
        param.put("path",priceTemplateId);
        param.put("name",vouchercode);
        String str=HttpUtil.post(url,param.toJSONString());
        JSONObject jsonObject=JSONObject.parseObject(str);
         if("200".equals(jsonObject.getString("code"))){
             JSONObject data=jsonObject.getJSONObject("data");
             if(!CollectionUtils.isEmpty(data.getJSONArray("recordList"))){
                 return  true;
             }
         }
         return  false;
    }


}
